package com.project.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.server.dto.LoginRequest;
import com.project.server.dto.UserLoginResponse;
import com.project.server.exception.BusinessException;
import com.project.server.mapper.UserMapper;
import com.project.server.model.User;
import com.project.server.service.UserService;
import com.project.server.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public UserLoginResponse login(LoginRequest request) {
        // 查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, request.getUsername()));

        if (user == null) {
            throw new BusinessException("用户名或密码错误");
        }

        // 验证密码
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        // 生成token
        String token = JwtUtil.generateToken(user.getId(), user.getUsername());

        // 清除敏感信息
        user.setPassword(null);

        // 返回登录响应
        return UserLoginResponse.builder()
                .token(token)
                .userInfo(user)
                .build();
    }

    @Override
    public void register(User user) {
        // 检查用户名是否已存在
        User userModel = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername,user.getUsername()));
        if (userModel != null) {
            throw new BusinessException("用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置默认状态
        user.setStatus(1);

        userMapper.insert(user);
    }

    @Override
    public User getCurrentUser(HttpServletRequest request) {
        Long userId = JwtUtil.getUserIdFromRequest(request);
        User user = userMapper.selectById(userId);
        if (user != null) {
            user.setPassword(null);
        }
        return user;
    }

    @Override
    public void update(User user,HttpServletRequest request) {
        Long userId = JwtUtil.getUserIdFromRequest(request);
        user.setId(userId);

        // 如果要修改密码，需要加密
        if (user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        userMapper.updateById(user);
    }

    @Override
    public Page<User> page(Integer page, Integer pageSize, String username, String phone) {
        return page(new Page<>(page, pageSize),
                new LambdaQueryWrapper<User>()
                        .like(StringUtils.isNotBlank(username), User::getUsername, username)
                        .like(StringUtils.isNotBlank(phone), User::getPhone, phone)
                        .orderByDesc(User::getCreateTime));
    }

    @Override
    public void create(User user) {
        // 检查用户名是否已存在
        if (baseMapper.exists(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, user.getUsername()))) {
            throw new BusinessException("用户名已存在");
        }

        // 检查手机号是否已存在
        if (StringUtils.isNotBlank(user.getPhone()) &&
                baseMapper.exists(new LambdaQueryWrapper<User>()
                        .eq(User::getPhone, user.getPhone()))) {
            throw new BusinessException("手机号已存在");
        }

        // 检查邮箱是否已存在
        if (StringUtils.isNotBlank(user.getEmail()) &&
                baseMapper.exists(new LambdaQueryWrapper<User>()
                        .eq(User::getEmail, user.getEmail()))) {
            throw new BusinessException("邮箱已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置创建时间
        user.setCreateTime(LocalDateTime.now());

        // 保存用户
        save(user);
    }
}
